package com.heima.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
@Slf4j
@Order(0)
public class AuthorizeFilter implements GlobalFilter {

    private static List<String> urlList = new ArrayList<>();

    // 初始化白名单 url路径
    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }

    /**
     * @param exchange 封装了请求和响应
     * @param chain    过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.检查用户的请求路径 是否属于白名单
        String path = request.getURI().getPath();
        for (String url : urlList) {
            if (path.contains(url)) {
                return chain.filter(exchange); //放行请求
            }
        }
        //  属于 直接放行
        //2. 获取请求头中的token  如果token不存在  直接终止请求  返回401
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
////            return response.setComplete(); //终止
            return writeMessage(exchange,"请求中不包含 token信息");
        }
        //3.解析token 判断token是否有效

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            //-1：有效，0：有效，1：过期，2：过期
            if (i<1){
                //3.1 如果 token有效 取出token中的用户id  重新在设置到请求头中 并放行请求
                Object id = claimsBody.get("id");
                log.info("用户通过网关认证成功 当前用户id：{}",id);
                //修改request
                request.mutate().header("userId",String.valueOf(id));
                //修改exchange
                exchange.mutate().request(request);
                return chain.filter(exchange);//放行
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        //3.2 如果 token无效 终止请求返回401
        return writeMessage(exchange,"token认证失败");
//        response.setStatusCode(HttpStatus.UNAUTHORIZED);
//        return response.setComplete(); //终止
    }
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}